<template>
  <div class="widget_data_grounp">
    <ZVirtualCascader v-model="value"
                      clearable
                      ref="cascader"
                      :key="cascaderKey"
                      separator=" / "
                      @change="onChange"
                      popperClass="z-virtual-cascader-popper__outer"
                      :props="props">
      <template slot-scope="{data}">
        <ZTooltip :line="1"
                  v-if="!data.status"
                  placement="left"
                  :content="data.label">
          <span style="width:150px">{{ data.label }}</span>
        </ZTooltip>

        <CascaderNode :data="data" :type="type"
                      v-else />
      </template>
      <template v-slot:suggestion="item">
        <div class="flex items-center">
          <ZTooltip :line="1"
                    placement="left"
                    popperClass="z-tooltip__outer"
                    :content="item.label.join(' / ')"
                     :toolTipType="'botWidget'"
                    >
            <span style="width:250px;margin-right:10px">{{item.label.join(' / ')}}</span>
          </ZTooltip>

          <ZTag round
                size="mini"
                :style="color(item.record.status)">
            {{item.record.status}}
          </ZTag>
        </div>

      </template>
    </ZVirtualCascader>

   <el-tooltip :open-delay="1000" :content="$t('custom.report.gaugebuildertip')"
                placement="top">
      <div class="cuifont icon_edit iconfont-normal"
           @click="priviewWidget"
           v-if="showIcon"></div>
    </el-tooltip>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelBeforeClosed="queryModelBeforeClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting" />
  </div>

</template>
<script>
import ZVirtualCascader from '@/components/storybook/z-virtual-cascader'
import ZTag from '@/components/storybook/z-tag'
import ZTooltip from '@/components/storybook/z-tooltip'
import { CascaderNode } from '@/components/select-dataset-group'
import { fetchDropWidget, fetchWidgetInfo, fetchDropIntegration } from '@/api/new'
import { v4 } from 'uuid'
import { toLower, get } from 'lodash'

export default {
  name: 'widget_data_grounp',
  props: {
    isBot: Boolean,
    businessType: Boolean,
    defaultValue: String,
    width: String,
    placeholder: String,
    showIcon: Boolean,
    type: String
  },
  components: { model: () => import('@/components/gadget/query-model/query-model'), ZVirtualCascader, CascaderNode, ZTooltip, ZTag },
  data () {
    return {
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {},
          reuse: true
        }
      },

      props: {
        multiple: false,
        checkStrictly: false,
        value: 'value',
        label: 'label',
        leaf: 'leaf',
        lazyLoad: async (nodeValue, resolve) => {
          if (nodeValue === 0) {
            const integrations = await this.getIntegrations()
            const options = integrations.map(({ code, name, rest }) => ({
              ...rest,
              label: name,
              value: code,
              leaf: false
            }))
            resolve(options)
          } else {
            const { records = [] } = await this.getWidgets({ size: 999999, current: 1, integrationCode: nodeValue })
            const options = records.map(({ gadgetId, name, ...rest }) => ({
              ...rest,
              label: name,
              value: gadgetId,
              leaf: true
            }))

            resolve(options)
          }
        },
        lazySearch: async (query, list = [], resolve) => {
          const [code, name] = query || []
          const integration = list.find(item => code && toLower(item.label).indexOf(toLower(code)) !== -1) || {}
          const { records = [] } = await this.getWidgets({ size: 999999, current: 1, integrationCode: integration.value, name })

          const options = records.reduce((result, record) => {
            const integrationList = record.integrationList || []
            const list = integrationList.map(({ code, name }) => ({
              record,
              value: [code, record.gadgetId],
              label: [name, record.name]
            }))
            return [...result, ...list]
          }, [])

          resolve(options)
        }
      },
      value: [],
      cascaderKey: v4()
    }
  },
  created () {
    this.init()
  },

  methods: {
    color (status) {
      switch (status) {
        case 'In-Dev':
          return { color: '#F56C6C', backgroundColor: '#FFF1F0' }

        case 'Published':
          return { color: '#67C23A', backgroundColor: '#EEF5DC' }

        case 'Alpha':
          return { color: '#E6A23C', backgroundColor: '#F2F2F2' }

        case 'In-QA':
          return { color: '#909399', backgroundColor: '#F2F2F2' }

        case 'Requested':
          return { color: '#138DC7', backgroundColor: '#E6F7FF' }
      }
    },
    isLinked (subjectCode) {
      var arr = this._.filter(this._.filter(this.$store.state.user.integrationList, { 'group': 1 }), { 'subjectCode': subjectCode })
      return arr.length > 0
    },
    async init () {
      if (get(this.$route, 'query.gadgetId')) {
        this.$emit('widgetSelecteChange', get(this.$route, 'query.gadgetId'))
      }

      if (this.defaultValue || get(this.$route, 'query.gadgetId')) {
        const { gadgetId, integrationCode } = await this.getWidgetInfo(this.defaultValue || get(this.$route, 'query.gadgetId'))
        let code = Array.isArray(integrationCode) && integrationCode.length ? integrationCode[integrationCode.length - 1] : 'no integration'
        if (integrationCode.length > 1) {
          code = integrationCode.find(i => this.isLinked(i))
        }
        this.value = [code, gadgetId]
        this.cascaderKey = v4()
      }
    },
    async priviewWidget () {
      var _self = this
      if (_self.value.length) {
        try {          
          const gadgetId = this.value[1]
          const { businessId, gadgetType } = await this.getWidgetInfo(gadgetId)
          _self.queryModelDefaultSetting.dataInfo.gadgetId = gadgetId
          _self.queryModelDefaultSetting.dataInfo.businessId = businessId
          _self.queryModelDefaultSetting.dataInfo.gadgetType = gadgetType
          _self.$store.state.isWidget = true
          _self.queryModelDefaultSetting.showSetting = true
        } catch (error) {

        }
      }
    },
    async getIntegrations () {
      const params = {
        reuse: true,
        type: 1,
        showAllIntegration: false,
        internal: false,
        cardQuery:{resourceType:1}
      }
      const { data: response } = await fetchDropIntegration(params)
      if (response.code !== 0) {
        return []
      }

      return response.data || []
    },
    async getWidgets (data) {
      const internal = this.isBot ? this.$store.state.bot.businessType === 'MSPbots Internal' : this.businessType
      const params = {
        reuse: true,
        type: 1,
        showAllIntegration: false,
        internal,
        resourceType: internal?110:1,
        ...data
      }
      const { data: response } = await fetchDropWidget(params)
      if (response.code !== 0) {
        return {}
      }

      return response.data || {}
    },
    async getWidgetInfo (gadgetId) {
      const params = {
        gadgetId,
        includeSql: true
      }
      const { data: response } = await fetchWidgetInfo(params)
      if (response.code !== 0) {
        return {}
      }
      return response.data || {}
    },
    onChange (value) {
      if (value) this.$emit('widgetSelecteChange', value[1])
    },
    queryModelBeforeClosed (val) {
      if (val) {
        this.$emit('widgetChanged', this.value[1])
      }
      this.queryModelDefaultSetting.showSetting = false
    },
    upgradeGadgetSetting () { }

  }
}
</script>
<style scoped lang='scss'>
.iconfont-normal {
  width: 28px;
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  margin-left: 10px;
  cursor: pointer;
  &:hover {
    background-color: $--theme-color-background;
    color: $--theme-color;
  }
}
</style>
<style lang="scss">
.widget_data_grounp {
  display: flex;
  .data_type_icon {
    span:nth-child(1) {
      color: #17b3a3;
    }
  }
}
.z-virtual-cascader-popper__outer {
  .el-cascader-node__label {
    white-space: inherit;
  }
}
.z-tooltip__outer {
  width: 250px;
}
</style>
